package com.lmm.cg.zjgcg.utils;

import android.util.Log;

import com.lmm.cg.zjgcg.config.ConfigValue;
import com.lmm.cg.zjgcg.task.BaseTask;
import com.lmm.cg.zjgcg.task.TaskCallBack;
import com.lmm.dresswisdom.lmmframe.util.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import io.reactivex.ObservableEmitter;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 上传文件方式
 */
public class UploadFileUtil {


    /**
     * 简易案件上传图片
     *
     * @param uploadCallback
     */
    public void uploadJXAJ(final String YeWuGuid, final String uploadType, final File mfile, final String refreshToken, final String accessToken, final TaskCallBack<String> uploadCallback) {

        new BaseTask<HashMap<String, String>>(uploadCallback) {
            @Override
            public void exec(ObservableEmitter emitter) {

                OkHttpClient client = new OkHttpClient();
                MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
                Map<String, String> params = new HashMap<>();
                try {
                    params.put("FileStream", FileUtils.encodeBase64File(mfile).replaceAll("[\\s*\t\n\r]", ""));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                params.put("YeWuGuid", YeWuGuid);
                params.put("FileType", "image");
                params.put("PicType", "jpg");
                if (uploadType.equals("jycxPj")) {
                    // 票据 01 证据 02
                    params.put("Type", "01");
                } else {
                    params.put("Type", "02");
                }

                params.put("RefreshToken", refreshToken);
                params.put("AccessToken", accessToken);

                String paramStr = generateRequestBodyStr(params);

                RequestBody body = RequestBody.create(mediaType, paramStr);
                Request request = new Request.Builder()
                        .url(ConfigValue.API_Upload_Url + "/UploadFile_JYCX")
                        .addHeader("Connection", "keep-alive")
                        .post(body).build();
                try {
                    Response response = client.newCall(request).execute();
                    emitter.onNext(response.body().string());
                    emitter.onComplete();
                } catch (IOException e) {
                    e.printStackTrace();
                    emitter.onError(null);
                }
            }
        }.run();
    }


    private String generateRequestBodyStr(Map<String, String> requestDataMap) {
        String bodystr = "";
        for (String key : requestDataMap.keySet()) {

            bodystr += key + "=" + URLEncoder.encode(requestDataMap.get(key)) + "&";
            Log.i("Eric", key + "//" + URLEncoder.encode(requestDataMap.get(key)));
        }
        return bodystr;
    }

    /**
     * 违停案件
     */
    public void uploadWT(final String YeWuGuid, final File mfile, final String refreshToken, final String accessToken, final TaskCallBack<String> uploadCallback) {
        new BaseTask<HashMap<String, String>>(uploadCallback) {
            @Override
            public void exec(ObservableEmitter emitter) {

                OkHttpClient client = new OkHttpClient();
                MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
                Map<String, String> params = new HashMap<>();
                try {
                    params.put("FileStream", FileUtils.encodeBase64File(mfile).replaceAll("[\\s*\t\n\r]", ""));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                params.put("YeWuGuid", YeWuGuid);
                params.put("FileType", "image");
                params.put("PicType", "jpg");
                params.put("RefreshToken", refreshToken);
                params.put("AccessToken", accessToken);

                String paramStr = generateRequestBodyStr(params);

                RequestBody body = RequestBody.create(mediaType, paramStr);
                Request request = new Request.Builder()
                        .url(ConfigValue.API_Upload_Url + "/UploadFile")
                        .addHeader("Connection", "keep-alive")
                        .post(body).build();
                try {
                    Response response = client.newCall(request).execute();
//                    Log.d("Eric", response.body().string());
                    emitter.onNext(response.body().string());
                    emitter.onComplete();
                } catch (IOException e) {
                    e.printStackTrace();
                    emitter.onError(null);
                }
            }
        }.run();
    }


    /**
     * 一般案件
     */
    public void uploadYBAJ(final String YeWuGuid, final File mfile, final String flag, final String refreshToken, final String accessToken, final TaskCallBack<String> uploadCallback) {
        new BaseTask<HashMap<String, String>>(uploadCallback) {
            @Override
            public void exec(ObservableEmitter emitter) {

                OkHttpClient client = new OkHttpClient();
                MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
                Map<String, String> params = new HashMap<>();
                try {
                    params.put("FileStream", FileUtils.encodeBase64File(mfile).replaceAll("[\\s*\t\n\r]", ""));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                params.put("YeWuGuid", YeWuGuid);
                params.put("FileType", "image");
                params.put("PicType", "jpg");
                params.put("RefreshToken", refreshToken);
                params.put("AccessToken", accessToken);
                if (flag.equals("ybaj_zj")) {
                    params.put("Flag", "ajzj");
                } else {
                    params.put("Flag", "xcczws");
                }

                String paramStr = generateRequestBodyStr(params);

                RequestBody body = RequestBody.create(mediaType, paramStr);
                Request request = new Request.Builder()
                        .url(ConfigValue.API_Upload_Url + "/YBAJ_TPUpload")
                        .addHeader("Connection", "keep-alive")
                        .post(body).build();
                try {
                    Response response = client.newCall(request).execute();
                    emitter.onNext(response.body().string());
                    emitter.onComplete();
                } catch (IOException e) {
                    e.printStackTrace();
                    emitter.onError(null);
                }
            }
        }.run();
    }

    // 双随机反馈
    public void uploadSSJFK(final String YeWuGuid, final File mfile, final String refreshToken, final String accessToken, final TaskCallBack<String> uploadCallback) {
        new BaseTask<HashMap<String, String>>(uploadCallback) {
            @Override
            public void exec(ObservableEmitter emitter) {

                OkHttpClient client = new OkHttpClient();
                MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
                Map<String, String> params = new HashMap<>();
                try {
                    params.put("FileStream", FileUtils.encodeBase64File(mfile).replaceAll("[\\s*\t\n\r]", ""));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                params.put("YeWuGuid", YeWuGuid);
                params.put("FileType", "image");
                params.put("RefreshToken", refreshToken);
                params.put("AccessToken", accessToken);

                String paramStr = generateRequestBodyStr(params);

                RequestBody body = RequestBody.create(mediaType, paramStr);
                Request request = new Request.Builder()
                        .url(ConfigValue.API_Upload_Url + "/FK_TPUpload")
                        .addHeader("Connection", "keep-alive")
                        .post(body).build();
                try {
                    Response response = client.newCall(request).execute();
                    emitter.onNext(response.body().string());
                    emitter.onComplete();
                } catch (IOException e) {
                    e.printStackTrace();
                    emitter.onError(null);
                }
            }
        }.run();
    }


    public void uploadSSJHF(final String YeWuGuid, final File mfile, final String refreshToken, final String accessToken, final TaskCallBack<String> uploadCallback) {
        new BaseTask<HashMap<String, String>>(uploadCallback) {
            @Override
            public void exec(ObservableEmitter emitter) {

                OkHttpClient client = new OkHttpClient();
                MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
                Map<String, String> params = new HashMap<>();
                try {
                    params.put("FileStream", FileUtils.encodeBase64File(mfile).replaceAll("[\\s*\t\n\r]", ""));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                params.put("YeWuGuid", YeWuGuid);
                params.put("FileType", "image");
                params.put("RefreshToken", refreshToken);
                params.put("AccessToken", accessToken);

                String paramStr = generateRequestBodyStr(params);

                RequestBody body = RequestBody.create(mediaType, paramStr);
                Request request = new Request.Builder()
                        .url(ConfigValue.API_Upload_Url + "/HF_TPUpload")
                        .addHeader("Connection", "keep-alive")
                        .post(body).build();
                try {
                    Response response = client.newCall(request).execute();
                    emitter.onNext(response.body().string());
                    emitter.onComplete();
                } catch (IOException e) {
                    e.printStackTrace();
                    emitter.onError(null);
                }
            }
        }.run();
    }

    /**
     * 删除图片
     *
     * @param filePath
     * @param uploadType
     * @param uploadCallback
     */
    public void deleteNetFile(String filePath, final String uploadType, final String refreshToken, final String accessToken, final TaskCallBack<String> uploadCallback) {
        int attindex = filePath.indexOf("AttachStorage");
        String sub = filePath.substring(attindex);

        String[] items = sub.split(File.separator);

        final String ywType = items[1];
        final String guid = items[2];


        int lastIndex = sub.lastIndexOf(File.separator);
        final String fileName = sub.substring(lastIndex + 1);

        new BaseTask<HashMap<String, String>>(uploadCallback) {
            @Override
            public void exec(ObservableEmitter emitter) {

                OkHttpClient client = new OkHttpClient();
                MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
                Map<String, String> params = new HashMap<>();
                String type = "";
                switch (ywType) {
                    case "YBAJ":
                        if (uploadType.equals("ybaj_zj")) {
                            type = "4";
                        } else {
                            type = "5";
                        }
                        break;
                    case "JYAJ":
                        // 区分票据还是证据
                        if (uploadType.equals("jycxPj")) {
                            type = "2";
                        } else {
                            type = "3";
                        }
                        break;
                    case "FK":
                        type = "6";
                        break;
                    case "HF":
                        type = "7";
                        break;
                    case "WT":
                        type = "1";
                        break;
                }

                params.put("FileName", fileName);
                params.put("YeWuGuid", guid);
                params.put("Type", type);
                params.put("RefreshToken", refreshToken);
                params.put("AccessToken", accessToken);

                String paramStr = generateRequestBodyStr(params);

                RequestBody body = RequestBody.create(mediaType, paramStr);
                Request request = new Request.Builder()
                        .url(ConfigValue.API_Upload_Url + "/DelPicture")
                        .addHeader("Connection", "keep-alive")
                        .post(body).build();
                try {
                    Response response = client.newCall(request).execute();
                    emitter.onNext(response.body().string());
                    emitter.onComplete();
                } catch (IOException e) {
                    e.printStackTrace();
                    emitter.onError(null);
                }
            }
        }.run();
    }
}
